/**
 *
 * @param input 输入的源
 * @param rowColumns 一行多少列
 */
export function extractQuestions(input: string, rowColumns: number = 3): string[] {
  let text = input.trim().replace(/(\r\n|\n\r)+/, '\n');
  
  const rs: string[] = [];
  
  // 逐行解析
  text.split(/\n/).forEach(row => {
    // const items = row.match(/[\S]{2,}/g) || [];
    const items = row.split(/[\s]{2,}/g).filter(Boolean)
    const max = Math.ceil(items.length / rowColumns) * rowColumns;
    for (let i = 0; i < max; i++) {
      rs.push(items[i] || '');
    }
  });
  
  return rs;
}

const Tokens = {
  '×': '*',
  '÷': '/',
  '＋': '+',
  '－': '-',
  '（': '(',
  '）': ')',
};

function generateTokensPattern(tokens: Record<string, string>): RegExp {
  const temp = Object.keys(tokens).join('|');
  return new RegExp(`\\s?${temp}\\s?`, 'g');
}

// @ts-ignore
let TokensPattern = generateTokensPattern(Tokens);

export function fixRound(str: string): string {
  if (isNaN(Number(str))) {
    return str
  }
  const match = str.match(/^([\d]+(?:\.[0]{0,}[^0]+)?)/);
  if (match) {
    return match[1];
  }
  return str;
}

export function calculateQuestion(input: string): string {
  try {
    const text = input.replace(TokensPattern, (search) => {
      const v = search.trim();
      // @ts-ignore
      return Tokens[v] || v;
    });
    const rs = eval(text);
    const int = parseInt(rs);
    if (int === rs) {
      return int + '';
    }
    return fixRound(rs.toFixed(8));
  } catch (err) {
  
  }
  return '';
}

const PurgeTokens = {
  '＋': '+',
  '－': '-',
  '（': '(',
  '）': ')',
};

export function purgeQuestion(input: string): string {
  return input.replace(/[\s]/g, '').replace(TokensPattern, (search) => {
    const v = search.trim();
    // @ts-ignore
    return PurgeTokens[v] || v;
  });
}